import { ActionContext } from 'vuex';
import { IUserState } from './state';
import { login } from '@/api/menu';
import { ACCESS_TOKEN, CURRENT_USER } from '@/store/mutation-types';
import { storage } from '@/utils/Storage';
import { IStore } from '@/store/types';

export const actions = {
  // 登录
  async login({ commit }: ActionContext<IUserState, IStore>, userInfo) {
    try {
      const response = await login(userInfo);
      const { retData, retCode } = response;
      if (retCode == 0) {
        const ex = 7 * 24 * 60 * 60 * 1000;
        storage.set(ACCESS_TOKEN, retData.loginId, ex);
        storage.set(CURRENT_USER, retData, ex);
        commit('setToken', retData.token);
        // todo
        commit('setUserInfo', retData);
      }
      return Promise.resolve(response);
    } catch (e) {
      return Promise.reject(e);
    }
  },

  // 登出
  async logout() {
    storage.clear();
    return Promise.resolve('');
  },

  async setDeviceType({ commit }: ActionContext<IUserState, IStore>, device) {
    console.log(device);
    commit('setType', device);
  }
};
